<?php
/**
 * User:ayou chow
 * Date: 2019-11-26
 * Time: 14:46
 */

namespace app\admin\controller;


use app\common\model\OrderModel;
use app\common\model\UserModel;
use app\common\model\UserProfitModel;
use think\Db;
use think\facade\Request;

class OrderController extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function edit()
    {
        $order = OrderModel::get(Request::param("id"));
        $this->assign("orderinfo", $order);
        return $this->fetch();
    }

    public function getlist()
    {
        $model = OrderModel::field('*');

        if ($order_no = trim($this->get('order_no', ''))) {
            $model = $model->where('order_no', $order_no);
        }

        if ($out_trade_no = trim($this->get('out_trade_no', ''))) {
            $model = $model->where('out_trade_no', $out_trade_no);
        }

        if (ctype_digit($uid = trim($this->get('uid', '')))) {
            $model = $model->where('uid', $uid);
        }

        if (in_array($type = $this->get('type', ''), ['0', '1'])) {
            $model = $model->where('type', $type);
        }

        if (in_array($is_manual = $this->get('is_manual'), ['0', '1'])) {
            $model = $model->where('is_manual', $is_manual)->where('pay_status', 1);
        } else {
            if (in_array($pay_status = $this->get('pay_status', ''), ['0', '1', '2', '3'])) {
                $model = $model->where('pay_status', $pay_status);
            }
        }

        if ($operator = trim($this->get('operator', ''))) {
            $model->where('operator', $operator);
        }

        $start_time = trim($this->get('start_time', ''));
        $end_time   = trim($this->get('end_time', ''));
        if ($start_time && $end_time) {
            $model = $model->whereBetween('create_time', [$start_time, $end_time]);
        } elseif ($start_time) {
            $model = $model->whereBetween('create_time', [$start_time, date('Y-m-d H:i:s')]);
        }

        // 排序
        $order     = "create_time desc";
        $field_str = Request::get('field', '', 'trim');
        $order_str = Request::get('order', '', 'trim');
        if ($field_str && $order_str) {
            $order = sprintf("%s %s", $field_str, $order_str);
        }

        return json([
            "count"  => $model->count('id'),
            "data"   => $model->with(['user' => function ($query) {
                $query->field('id, nick_name');
            }])->order($order)
                ->page($this->get('page', 1), $this->get('limit', 20))
                ->select()->each(function ($query) {
                    $query->gold_added = bcdiv(strval($query->gold_added), '100', 2);
                    $query->gold       = bcdiv(strval($query->gold), '100', 2);
                }),
            'statis' => $this->statisCompute('count', 6),
            "code"   => 0,
            "msg"    => "",
        ]);
    }

    public function edit_post()
    {
        $order = OrderModel::where(['id' => Request::param('id')])->find();
        if (!$order) {
            return self::bulidFail("订单不存在");
        }
        if ($order->pay_status == 1) {
            return self::bulidFail("该订单已支付");
        }
        $param               = Request::param();
        $param["pay_status"] = 1;
        $param["operator"]   = $this->admin_name;
        $param['is_manual']  = 1;
        $param["pay_time"]   = date('Y-m-d H:i:s');
        // if ($order->amount > 0) {
        //     $param["co_amount"] = bcmul($order->amount, 0.7, 2);
        // }

        $user = UserModel::where(['id' => $order->uid])->find();
        if (!$user) {
            return self::bulidFail("用户不存在");
        }

        Db::startTrans();
        try {
            if (!$order->save($param)) {
                throw new \Exception('修改订单失败');
            }

            if ($order->type != 0) {
                Db::rollback();
                return self::bulidFail("暂不支持非金币类型充值");
            }
            $gold       = bcadd($order->gold, $order->gold_added);
            $gold_cny   = bcdiv($gold, 100, 2);
            $user->gold = ['inc', $gold];

            $uprofit_data = [
                'consume_type' => 100,
                'uid'          => $user->id,
                'coin_count'   => $gold,
                'type'         => 1,
                'coin_type'    => 1,
                'content'      => "会员id({$user->id})购买：{$gold_cny}金币 充值收入",
                'remark'       => '',
                'resid'        => 0,
                'count'        => 1,
                'order_no'     => $order->order_no,
                'liveid'       => 0,
                'create_time'  => date('Y-m-d H:i:s')
            ];
            $user_profit  = new UserProfitModel($uprofit_data);
            if (!$user_profit->save()) {
                throw new \Exception('设置用户流水失败');
            }

            if (!$user->save()) {
                throw new \Exception('设置用户金额失败');
            }

            //写管理员操作日志
            $log_content = "将用户{$user->nick_name}({$user->id})的充值订单ID为：{$order->id}，单号：{$order->order_no}，状态修改为支付成功";
            parent::addAdminLog($log_content, $user->id);

            Db::commit();
            return self::bulidSuccess();

        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()]);
        }
        return self::bulidFail("设置失败");
    }

    public function del_post()
    {
        return self::bulidFail('操作错误');
        $id          = Request::param('id');
        $order_model = OrderModel::get($id);
        if (!$order_model) {
            return self::bulidFail('订单不存在');
        }
        if (OrderModel::destroy($id)) {
            // 记录日志
            $log_content = "删除订单，用户ID：{$order_model->uid}，单号：{$order_model->order_no}，金额：{$order_model->pay_amount}，状态：{$order_model->pay_status_text}";
            parent::addAdminLog($log_content, $order_model->uid);

            return self::bulidSuccess();
        }

        return self::bulidFail();
    }


    /**
     * 用户充值记录
     * @return mixed
     */
    public function user_order()
    {
        $uid = Request::param('uid');
        $this->assign('uid', $uid);
        return $this->fetch();
    }

    /**
     * 用户充值记录数据
     * @return \think\response\Json
     */
    public function getuserOrderlist()
    {
        $where            = [];
        $where_time_start = '';
        $where_time_end   = '';

        $uid        = Request::param('uid');
        $type       = Request::param('type', 0);
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        $page       = Request::param("page", 1);
        $limit      = Request::param("limit");

        if ($uid < 1) {
            return self::bulidFail("未查询到相关数据");
        }

        $where["uid"] = $uid;

        switch ($type) {
            case 1:
                // 今日
                $day_time = date('Y-m-d 00:00:00');
                $end_time = date('Y-m-d 23:59:59');
                break;
            case 2:
                // 昨日
                $day_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                // 最近7天
                $day_time = date('Y-m-d 00:00:00', strtotime('-7 days'));
                break;
            case 4:
                // 最近30天
                $day_time = date('Y-m-d 00:00:00', strtotime('-30 days'));
                break;
        }

        if (isset($day_time)) {
            $where_time_start = "create_time > '{$day_time}'";
        }
        if ($start_time) {
            $where_time_start = "create_time > '{$start_time}'";
        }
        if ($end_time) {
            $where_time_end = "create_time < '{$end_time}'";
        }

        $orders = OrderModel::where($where)->where($where_time_start)->where($where_time_end)
            ->limit(($page - 1) * $limit, $limit)
            ->order("create_time", "desc")
            ->select()
            ->each(function ($query) {
                $query->gold       = $query->gold == 0 ? 0 : bcdiv($query->gold, '100', 2);
                $query->gold_added = $query->gold_added == 0 ? 0 : bcdiv($query->gold_added, '100', 2);

            });
        $count  = count($orders);
        if ($count > 0) {
            $count = OrderModel::where($where)->where($where_time_start)->where($where_time_end)->count("id");
            return json(["code" => 0, "msg" => "", "data" => $orders, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }


    /**
     * 统计
     * @return \think\response\Json
     */
    public function statis()
    {
        // 今日
        $today = $this->statisCompute('today', 1);
        // 昨日
        $yesterday = $this->statisCompute('yesterday', 2);
        // 最近7天
        $seven_day = $this->statisCompute('sevenday', 3);
        $seven_day = [];
        // 本月
        $this_month = $this->statisCompute('thismonth', 4);
        // 上个月
        $last_month = $this->statisCompute('lastmonth', 5);
        // 合并数组
        $data = array_merge($today, $yesterday, $seven_day, $this_month, $last_month);

        return json(["code" => 0, "msg" => "", "data" => [$data], "count" => 1]);
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 统计计算
     * @param $flag 统计标示
     * @param $start_time
     * @param $end_time
     * @return array
     */
    private function statisCompute($flag = 'today', $type = 1)
    {
        switch ($type) {
            case 1:
                // 今日
                $start_time = date('Y-m-d 00:00:00');
                $end_time   = date('Y-m-d 23:59:59');
                break;
            case 2:
                // 昨日
                $start_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time   = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                // 最近7天
                $start_time = date('Y-m-d 00:00:00', strtotime('-6 days'));
                $end_time   = date('Y-m-d 23:59:59');
                break;
            case 4:
                // 本月
                $start_time = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), 1, date('Y')));
                $end_time   = date('Y-m-d 23:59:59');
                break;
            case 5:
                // 上个月
                $start_time = date("Y-m-d 00:00:00", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                $end_time   = date("Y-m-d 23:59:59", mktime(23, 59, 59, date("m"), 0, date("Y")));
                break;
            case 6:
                // 列表总统计数据
                $start_time = trim($this->get('start_time', ''));
                $end_time   = trim($this->get('end_time', ''));
                break;
        }

        $where = [];
        if (!empty($start_time)) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if (!empty($end_time)) {
            $where[] = ['create_time', '<=', $end_time];
        }

        $a_where = [
            ['pay_status', '=', 1],
        ];
        $info    = OrderModel::where($a_where)->where($where)->field("sum(pay_amount) as amount,count(id) as total")->find();
        $total   = OrderModel::where($where)->field("sum(pay_amount) as amount,count(id) as total")->find();
        $data    = [
            // 实收
            $flag . '_amount'        => isset($info->amount) ? number_format($info->amount, 2) : 0,
            // 总金额（包含未支付成功的）
            $flag . '_total_amount'  => isset($total->amount) ? number_format($total->amount, 2) : 0,
            // 总订单数
            $flag . '_total'         => !empty($total->total) ? number_format($total->total) : 0,
            // 成功订单数
            $flag . '_success_total' => !empty($info->total) ? number_format($info->total) : 0,
            // 支付成功比例
            $flag . '_rate'          => $total->total > 0 ? bcmul(($info->total / $total->total), 100, 2) : 0,
        ];
        return $data;
    }


    /**
     * 导出正式用户的充值，不包含人工到账
     * @return \think\response\Json
     */
    public function excel()
    {
        // 排除测试账号
        $test_uids = UserModel::where('is_test', 1)->column('id');
        $where     = [
            ['amount', '>', 0],
            ['is_manual', '=', 0],
            ['pay_status', '=', 1],
            ['uid', 'not in', $test_uids]
        ];

        $order_model = OrderModel::with([
            'userobj' => function ($query) {
                $query->field('id, nick_name,is_test');
            }
        ])->where($where);


        $list = [];
        $order_model->chunk(500, function ($querys) use (&$list) {
            foreach ($querys as $query) {
                if (!$query->userobj) {
                    continue;
                }
                $query->gold_added = bcdiv(strval($query->gold_added), '100', 2);
                $query->gold       = bcdiv(strval($query->gold), '100', 2);
                $list[]            = [
                    $query->id,
                    $query->userobj->id,
                    $query->userobj->nick_name,
                    $query->amount,
                    (string)$query->order_no,
                    $query->create_time,
                ];
            }
        }, 'id', 'desc');

        $file_title = [
            'ID', '用户ID', '用户昵称', '订单金额', '订单号', '下单时间'
        ];
        $file_name  = '订单列表' . date('Y年m月d日H点');

        return export_excel($list, $file_title, $file_name, '订单列表');
    }


}